package top.jacktgq.hsp.nio.selector;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author CandyWall
 * @Date 2020/11/11--16:36
 * @Description
 */
public class NIOServer {
    public static void main(String[] args) throws Exception {
        //创建ServerSocketChannel，跟ServerSocket的功能相似
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        
        //得到一个Selector对象
        Selector selector = Selector.open();

        //绑定一个端口6666，在服务器端监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));

        //设置为非阻塞模式
        serverSocketChannel.configureBlocking(false);

        //把ServerSocketChannel注册到selector，关心事件为OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("客户端连接后，注册的SelectionKey的数量：" + selector.keys().size());

        //循环等待客户端连接
        while (true) {

            //等待1秒，1秒后没有事件发生，返回
            if (selector.select(1000) == 0) {
                System.out.println("服务器等待了1秒，无连接");
                continue;
            }

            //如果返回>0，就获取到相关的SelectionKey集合
            //1、如果返回大于0，表示已经获取到关注的事件了
            //2、Selector.selectedKeys() 返回关注事件的集合
            //通过selectionKeys 反向获取通道
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            //遍历 Set<SelectionKey>，使用迭代器遍历
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                //获取到SelectionKey
                SelectionKey selectionKey = keyIterator.next();
                if (selectionKey.isAcceptable()) {  //如果是OP_ACCEPT，表示有新的客户端连接
                    //给该客户端生成一个SocketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功 生成了一个SocketChannel：" + socketChannel.hashCode());
                    //将socketChannel设置为非阻塞
                    socketChannel.configureBlocking(false);
                    //将socketChannel注册到Selector，关注事件为SelectionKey.OP_READ
                    //同时给该SocketChannel关联一个Buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));

                    System.out.println("客户端连接后，注册的SelectionKey的数量：" + selector.keys().size());
                    System.out.println("客户端连接后，SelectedKeys的数量：" + selector.selectedKeys().size());
                }

                if (selectionKey.isReadable()) {    //发生了OP_READ
                    //通过key，反向获取到对应的Channel
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    //通过key，反向获取到该Channel关联的Buffer
                    ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
                    socketChannel.read(byteBuffer);
                    System.out.println("来自客户端 " + socketChannel.getLocalAddress() + "的一条消息："
                                                 + new String(byteBuffer.array(), "UTF-8"));
                }
                //手动从集合中移除当前的SelectionKey，防止多线程环境下的重复操作
                keyIterator.remove();
            }
        }
    }
}
